package com.neuralnoise;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

import org.apache.log4j.Logger;

public abstract class AbstractCrawler<ID> {

	private Logger logger = Logger.getLogger(this.getClass());
	
	private AbstractDriver<ID> driver;
	
	public AbstractCrawler(AbstractDriver<ID> driver) {
		this.driver = driver;
	}
	
	public void breadthFirstGraphExploration(ID fid, Long millis) throws Exception {
		Set<ID> visited = new HashSet<ID>();

		Queue<ID> queue = new LinkedList<ID>();
		queue.add(fid);
		
		while (!queue.isEmpty()) {
			ID id = queue.poll();

			logger.info("Checking node " + id + ", frontier size: " + queue.size() + " ..");

			if (!visited.contains(id)) {
				visited.add(id);
			}

			boolean hasUserData = driver.hasUserData(id);

			if (!hasUserData) {
				driver.addUserData(id);
				Thread.sleep(millis);	
			}
			
			Collection<ID> connections = driver.getConnections(id);
			queue.addAll(connections);
		}
	}
	
}
